/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-04-10
 */
package TcpPack

//主动刷卡数据包
import (
	"encoding/binary"
	"io"
	"strings"
)

//主动上传刷卡规则
type CardPack struct {
	CarId string //卡号 长度20字节 Ascii字符串
	CarIdByte [20]byte //卡号 20字节
	CardType int8 //刷卡类型 1-ic卡 2-车辆vin
}


//刷卡回复数据包规则
type CardReplyPack struct {
	CardId string //卡号 长度20字节 Ascii字符串
	CardIdByte [20]byte //卡号 20字节
	Money int32 //余额 单位分
	CardState int8 //卡状态 0-可以充电 1-已经在充电 2-余额不足 3-已经挂失 4-无效卡
	SerialNo uint32 //后台交易流水号 无符号整型数
	MoneyMin int32 //卡片允许充电最低余额 单位分，用于控制卡片是否可以透支充电逻辑
	Retain [16]byte //保留 16字节
}

//解码
func (p *CardPack) Unpack(reader io.Reader) error{
	var err error
	err = binary.Read(reader, binary.LittleEndian, &p.CarIdByte)

	p.CarId= strings.ReplaceAll(string(p.CarIdByte[:]),"\x00","")

	err = binary.Read(reader, binary.LittleEndian, &p.CardType)

	return err
}

func (p *CardReplyPack) Pack(writer io.Writer) error{
	var err error
	//传递字符串卡号逻辑
	if p.CardId!=""{
		b:=[]byte(p.CardId)
		top:=20-len(b)
		for k,v:=range b{
			p.CardIdByte[k+top]=v
		}
	}
	//卡号
	err = binary.Write(writer, binary.LittleEndian, &p.CardIdByte)
	err = binary.Write(writer, binary.LittleEndian, &p.Money)
	err = binary.Write(writer, binary.LittleEndian, &p.CardState)
	err = binary.Write(writer, binary.LittleEndian, &p.SerialNo)
	err = binary.Write(writer, binary.LittleEndian, &p.MoneyMin)
	err = binary.Write(writer, binary.LittleEndian, &p.Retain)




	return err
}

